import Vue from "vue";
import VueRouter from "vue-router";
import Login from "@/views/login/login.vue";
import Layout from "@/views/layout/Layout";
import local from "@/utils/local.js";

Vue.use(VueRouter);
/**
 * 重写路由的push方法--->这个是vue-cli4.x以上的坑，不然的话，你是跳转不了的
 */
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}

/* 
  就是路由配置-从上往下开始找的
  看到404，*，都是放在最后最后的
*/

// 默认路由
const routes = [
  // 登录路由
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  // 登录后的，大路由
  {
    path: "/",
    name: "layout",
    component: Layout,
    redirect: '/home',
    children: [{
      path: '/home',
      component: () => import('@/views/Home.vue') // 懒加载的写法
    }]
  }
];

// 动态路由
const asyncRoutes = [
  // 登录
  {
    path: '/login',
    component: Login,
    visible: false
  },

  // 后端大布局

  // 首页
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    visible: true,
    meta: {
      icon: "icon-icon_home",
      title: "后台首页"
    },
    children: [{
      path: '/home',
      component: () => import('@/views/Home.vue') // 懒加载的写法
    }]
  },

  // 订单管理
  {
    path: '/order',
    component: Layout,
    redirect: '/order/order-list',
    visible: true,
    meta: {
      icon: "icon-orderedlist-selected",
      role: ["super"],
      title: "订单管理"
    },
    children: [{
        path: '/order/order-list',
        component: () => import('@/views/Order/OrderList.vue'), // 懒加载的写法
        meta: {
          title: "订单列表"
        }
      },
      {
        path: '/order/order-edit',
        component: () => import('@/views/Order/OrderEdit.vue'), // 懒加载的写法
        meta: {
          title: "订单编辑"
        }
      },

    ]
  },

  // 商品管理
  {
    path: '/goods',
    component: Layout,
    redirect: '/goods/goods-list',
    visible: true,
    meta: {
      icon: "icon-shangpin",
      role: ["super", "normal"],
      title: "商品管理"
    },
    children: [{
        path: '/goods/goods-list',
        component: () => import('@/views/Goods/GoodsList.vue'), // 懒加载的写法
        meta: {
          title: "商品列表"
        }
      },
      {
        path: '/goods/goods-add',
        component: () => import('@/views/Goods/GoodsAdd.vue'), // 懒加载的写法
        meta: {
          role: ["super"],
          title: "商品添加"
        }
      },
      {
        path: '/goods/goods-cate',
        component: () => import('@/views/Goods/GoodsCate.vue'), // 懒加载的写法
        meta: {
          title: "商品分类"
        }
      }

    ]
  },

  // 店铺管理
  {
    path: "/shop",
    component: Layout,
    visible: true,
    meta: {
      title: "店铺管理",
      icon: "icon-dianpu"
    },
    children: [{
      path: "",
      component: () => import("@/views/Shop.vue")
    }]
  },

  // 账号管理
  {
    path: "/account",
    component: Layout,
    redirect: "/account/account-list",
    visible: true,
    meta: {
      title: "账号管理",
      icon: "icon-zhanghao1",
      role: ["super", "normal"]
    },
    children: [{
        path: '/account/account-list',
        component: () => import('@/views/Account/AccountList.vue'), // 懒加载的写法
        meta: {
          role: ["super"],
          title: "账号列表"
        }
      },
      {
        path: '/account/account-add',
        component: () => import('@/views/Account/AccountAdd.vue'), // 懒加载的写法
        meta: {
          role: ["super"],
          title: "账号添加"
        }
      },
      {
        path: '/account/pass-modify',
        component: () => import('@/views/Account/PassModify.vue'), // 懒加载的写法
        meta: {
          title: "密码修改"
        }
      },
      {
        path: '/account/personal',
        component: () => import('@/views/Account/Personal.vue'), // 懒加载的写法
        meta: {
          title: "个人中心"
        }
      }

    ]
  },

  // 销售统计
  {
    path: "/total",
    component: Layout,
    redirect: "/total/goods-total",
    visible: true,
    meta: {
      title: "销售统计",
      icon: "icon-tongji",
      role: ["super"]
    },
    children: [{
        path: '/total/goods-total',
        component: () => import('@/views/Total/GoodsTotal.vue'), // 懒加载的写法
        meta: {
          title: "商品统计"
        }
      },
      {
        path: '/total/order-total',
        component: () => import('@/views/Total/OrderTotal.vue'), // 懒加载的写法
        meta: {
          title: "订单统计"
        }
      },

    ]
  },

  // 错误路由
  {
    path: "/404",
    name: "404",
    component: () => import("@/views/error/404.vue"),
    visible: false,
  },
  {
    path: "*",
    redirect: "/404",
    visible: false,
  },

]



const router = new VueRouter({
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  /* 
    to:你去哪里？
    from:你从哪里来
    next:1.放行  ， 2.强制跳转
  */

  // 判断是都登录成功
  let isLogin = local.get("t_k") ? true : false;
  if (isLogin) {
    next(); // 如果登录成功，直接放行
  } else {
    // 如果去的是登录页面
    if (to.path === "/login") {
      next(); // 去登录页面放行
    } else {
      next("/login"); // 否则去的就是别的页面，强行重置到登录页面
    }
  }
});

/**
 * created by itwangyang 2020-7-29
 * 封装动态路由
 * @description:判断当前路由对象，有没有权限
 * @param {router}:当前对象
 * @param {role}：当前角色
 * @returns:true有权限的，false是没有权限的
 */


// 路由权限
function hasPermission(router, role) {
  // 如果路由汇总有meta并且meta中还有role，证明是配置了权限管理，需要做权限验证
  if (router.meta && router.meta.role) {
    return router.meta.role.includes(role)
  } else {
    // 反之
    return true;
  }
}


/**
 * created by itwangyang 2020-7-29
 * @description:计算出当前角色有权限访问的路由--使用的是过滤器
 * @param {asyncRoutes}:动态路由
 * @param {role}: 角色
 * 
 */

function calcRoutes(asyncRoutes, role) {
  let accessRoutes = asyncRoutes.filter((router) => {
    if (hasPermission(router, role)) {
      if (router.children && router.children.length) {
        router.children = calcRoutes(router.children, role) // 递归过滤
      }
      return true
    } else {
      return false
    }
  });
  return accessRoutes
}



/**
 * created by itwangyang 2020-7-29
 * @description: 判断左侧菜单是否出现
 * 
 */


function isVisible(router, role) {
  if (router.visible) {
    return true
  } else {
    return false
  }
}



/**
 * created by itwangyang 2020-7-29
 * @description: 当前有权限访问的路由
 * 
 */

function calcMenus(accessRoutes, role) {
  let arr = accessRoutes.filter((router) => {
    if (isVisible(router, role)) {
      return true
    } else {
      return false
    }
  });
  return arr
}



/**
 * created by itwangyang 2020-7-29
 * @description: 根据角色，动态去创建出可以当前角色可以访问的路由
 */

export function createRoutes() {
  // 获取角色
  let role = local.get('role')
  //计算拿出有没有权限的访问的路由 
  let accessRoutes = calcRoutes(asyncRoutes, role)
  // 动态添加路由
  router.addRoutes(accessRoutes)
  let menus = calcMenus(accessRoutes, role)
  console.log(menus)
  // 存入本地
  local.set('menus', menus)
}

createRoutes();



export default router;